# -*- coding: utf-8 -*-

import atexit
import logging
import logging.config
import os
import sys
import traceback
from argparse import ArgumentParser

import util

reload(sys)
sys.setdefaultencoding('utf8')

WORKER_PATH = os.path.dirname(os.path.realpath(__file__))
TASK_NAME = ''


@atexit.register
def cleanup():
    logging.shutdown()


def do(task_cfg):
    pn = None if 'processor' not in task_cfg else task_cfg.pop('processor')
    assert pn

    p = util.create_class_instance(pn, task_cfg)
    assert p and hasattr(p, 'begin') and hasattr(p, 'end')

    try:
        p.begin()
    finally:
        p.end()


def main():
    argp = ArgumentParser()

    argp.add_argument('task_name')
    argp.add_argument('-e', dest='conf_path')
    argp.add_argument('-x', dest='task_xargs')
    argp.add_argument('--excfg-key', dest='excfg_key')

    args = argp.parse_args()

    global ENV_NAME
    global TASK_NAME
    global TASK_FULL_NAME

    task_cfg = {}

    try:
        sys.path.append('%s/conf/%s' % (WORKER_PATH, 'production' if not args.conf_path else args.conf_path))
        sys.path.append('%s/tasks' % WORKER_PATH)

        ENV_NAME = args.conf_path
        TASK_NAME = args.task_name
        TASK_FULL_NAME = '%s:%s' % (ENV_NAME, TASK_NAME)

        conf_module = __import__(TASK_NAME, fromlist=['*'])

        if hasattr(conf_module, 'PREPARE_FOR_DIRS') and conf_module.PREPARE_FOR_DIRS:
            [util.make_dirs(x) for x in conf_module.PREPARE_FOR_DIRS]

        if hasattr(conf_module, 'LOGGING_CFG') and conf_module.LOGGING_CFG:
            logging.config.dictConfig(conf_module.LOGGING_CFG)

        if hasattr(conf_module, 'CFG') and conf_module.CFG:
            task_cfg = conf_module.CFG
            task_cfg['env_name'] = ENV_NAME
            task_cfg['task_name'] = TASK_NAME
            task_cfg['task_full_name'] = TASK_FULL_NAME
            task_cfg['server'] = util.get_ip_address()
            if args.task_xargs:
                task_cfg['xargs'] = args.task_xargs
            if args.excfg_key:
                task_cfg['excfg_key'] = args.excfg_key
        else:
            raise Exception('Invalid configuration: [%s.CFG]' % TASK_NAME)

        del sys.modules[TASK_NAME]
        del conf_module
    except Exception as e:
        print task_cfg
        raise Exception('Failed to initialize : %s' % e)

    logger = logging.getLogger()

    logger.info('Start ...: %s' % TASK_NAME)
    logger.info('[TASK_CFG]: %s' % str(task_cfg))

    do(task_cfg)

    logger.info('End ...: %s' % TASK_NAME)


if __name__ == '__main__':
    try:
        main()
    except:
        traceback.print_exc()
